package com.weixing.mall.provider.support.wechat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.weixin4j.Weixin;
import org.weixin4j.WeixinException;
import org.weixin4j.loader.ITokenLoader;
import org.weixin4j.model.base.Token;

import java.util.concurrent.TimeUnit;

/**
 * @Author: kfc
 * @Description: 微信access_token工具类<br/>
 * Date:Create in 2018/11/12 14:43
 * @Modified By:
 */

@Component
public class AccessTokenLoader implements ITokenLoader {

    private static final String ACCESS_TOKEN_KEY = "access_token";

    @Autowired
    @Qualifier("redisTemplate")
    public  RedisTemplate redisTemplate;

    @Override
    public  Token get() {
        // 从redis中获取access_token
        Token token = (Token) redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);
        if (null == token){
            try {
                token = new Weixin().getToken();
            } catch (WeixinException e) {
                e.printStackTrace();
            }
            refresh(token);
        }
        return token;
    }

    @Override
    public void refresh(Token token) {

        redisTemplate.opsForValue().set("access_token", token,6600L, TimeUnit.SECONDS);
    }

}
